<template>
  <div class="message-center">
    <UserLayout>
      <div class="message-container">
        <el-card class="message-card">
          <template #header>
            <div class="card-header">
              <span>消息中心</span>
              <el-button @click="markAllAsRead" type="primary" size="small">
                全部标记为已读
              </el-button>
            </div>
          </template>

          <div class="message-tabs">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
              <el-tab-pane label="全部消息" name="all">
                <MessageList 
                  :messages="filteredMessages" 
                  :loading="loading"
                  @message-click="handleMessageClick"
                  @delete-message="handleDeleteMessage"
                />
              </el-tab-pane>
              
              <el-tab-pane label="系统通知" name="system">
                <MessageList 
                  :messages="systemMessages" 
                  :loading="loading"
                  @message-click="handleMessageClick"
                  @delete-message="handleDeleteMessage"
                />
              </el-tab-pane>
              
              <el-tab-pane label="用户消息" name="user">
                <MessageList 
                  :messages="userMessages" 
                  :loading="loading"
                  @message-click="handleMessageClick"
                  @delete-message="handleDeleteMessage"
                />
              </el-tab-pane>
              
              <el-tab-pane label="未读消息" name="unread">
                <MessageList 
                  :messages="unreadMessages" 
                  :loading="loading"
                  @message-click="handleMessageClick"
                  @delete-message="handleDeleteMessage"
                />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>

        <!-- 消息详情对话框 -->
        <el-dialog
          v-model="showMessageDetail"
          :title="selectedMessage?.title || '消息详情'"
          width="600px"
          @close="handleCloseDetail"
        >
          <MessageDetail 
            v-if="selectedMessage"
            :message="selectedMessage"
            @reply="handleReply"
          />
        </el-dialog>

        <!-- 回复消息对话框 -->
        <el-dialog
          v-model="showReplyDialog"
          title="回复消息"
          width="500px"
        >
          <ReplyForm 
            v-if="replyToMessage"
            :original-message="replyToMessage"
            @send="handleSendReply"
            @cancel="showReplyDialog = false"
          />
        </el-dialog>
      </div>
    </UserLayout>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import MessageList from '@/components/message/MessageList.vue'
import MessageDetail from '@/components/message/MessageDetail.vue'
import ReplyForm from '@/components/message/ReplyForm.vue'
import { getMessages, markMessageRead, sendMessage } from '@/utils/apiService'

// 响应式数据
const activeTab = ref('all')
const loading = ref(false)
const messages = ref([])
const selectedMessage = ref(null)
const showMessageDetail = ref(false)
const showReplyDialog = ref(false)
const replyToMessage = ref(null)

// 计算属性
const filteredMessages = computed(() => {
  return messages.value
})

const systemMessages = computed(() => {
  return messages.value.filter(msg => msg.type === 'system')
})

const userMessages = computed(() => {
  return messages.value.filter(msg => msg.type === 'user')
})

const unreadMessages = computed(() => {
  return messages.value.filter(msg => !msg.isRead)
})

// 方法
const loadMessages = async () => {
  loading.value = true
  try {
    const response = await getMessages()
    if (response.code === '200') {
      messages.value = response.data || []
    }
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  } finally {
    loading.value = false
  }
}

const handleTabChange = (tabName) => {
  activeTab.value = tabName
}

const handleMessageClick = async (message) => {
  selectedMessage.value = message
  showMessageDetail.value = true
  
  // 如果消息未读，标记为已读
  if (!message.isRead) {
    try {
      await markMessageRead(message.id)
      message.isRead = true
    } catch (error) {
      console.error('标记消息已读失败:', error)
    }
  }
}

const handleCloseDetail = () => {
  showMessageDetail.value = false
  selectedMessage.value = null
}

const handleDeleteMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里应该调用删除API
    messages.value = messages.value.filter(msg => msg.id !== messageId)
    ElMessage.success('消息删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const markAllAsRead = async () => {
  try {
    // 这里应该调用批量标记已读的API
    messages.value.forEach(msg => {
      msg.isRead = true
    })
    ElMessage.success('所有消息已标记为已读')
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleReply = (message) => {
  replyToMessage.value = message
  showReplyDialog.value = true
  showMessageDetail.value = false
}

const handleSendReply = async (replyData) => {
  try {
    await sendMessage(replyData)
    ElMessage.success('回复发送成功')
    showReplyDialog.value = false
    replyToMessage.value = null
    // 重新加载消息
    await loadMessages()
  } catch (error) {
    console.error('发送回复失败:', error)
    ElMessage.error('发送失败')
  }
}

// 生命周期
onMounted(() => {
  loadMessages()
})
</script>

<style scoped>
.message-center {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.message-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.message-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.message-tabs {
  margin-top: 20px;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
}
</style>
